//重新封装axios 请求
import axios from 'axios'
import { Loading, Message } from 'element-ui'

// 重新创建一个加载状态
let loadingStatus = true
//重新创建一个axios 实例，统一管理实例请求
// if (process.env.NODE_ENV === 'production') {
//   axios.defaults.baseURL = '/'
// } else {
//   axios.defaults.baseURL = 'https://smartiot.stardreamstudio.com/'
// }
const instance = axios.create({
  timeout: 10000,
  baseURL: '/api'
})
// baseUrl
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

instance.interceptors.request.use(config => {
  console.log("request",config)

  config.headers['token'] = sessionStorage.getItem('token') || ''

  if (config.headers['token']) {
    config.headers.Authorization = config.headers['token']
  }
  loadingStatus = Loading.service({
    spinner: 'fa fa-spinner fa-spin fa-3x fa-fw',
    text: '拼命加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  if (config.method === 'get') {
    config.headers['data'] = JSON.stringify({
      ...config.params
    })
    config.params = null
  }
  return config
}, error => {
  return Promise.reject(error)
})

instance.interceptors.response.use(res => {
  loadingStatus.close()
  console.log("response",res)
  if (res.status === 200) {

    if (res.Result) {
      // 提示请求的结果
      Message({
        type: 'success',
        message: res.data.Result
      })
    }
    return Promise.resolve(res.data)
  } else {
    Message({
      message: res.data.Result,
      type: 'error'
    })
    return Promise.reject(res.data)
  }
}, error => {
  loadingStatus.close()
  if (error.response) {
    // 根据请求失败的http状态码去给用户相应的提示

    let tips = error.response.data
    Message({
      message: tips.Reason,
      type: 'error'
    })
    return Promise.reject(new Error(tips))
  }
})
/* 统一封装get请求 */
export const get = (url, params, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'get',
      url,
      params,
      ...config
    }).then(response => {

      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

//统一封装post 请求
export const post = (url, data, config = {}) => {
  return instance({
    method: 'post',
    url,
    data,
    ...config
  }).then(response => {
    return Promise.resolve(response)
  }).catch(error => {
    return Promise.reject(error)
  })
}

// 统一封装delete请求
export const del = (url, params, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'delete',
      url,
      params,
      ...config
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}
//统一封装put 请求
export const put = (url, params, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'put',
      url,
      params,
      ...config
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}
//统一封装 ...
